function Requests()
{
	var labbyContainer = $("#labby");
	this.initInfoPopup = function(response)
	{
		var html = $.parseHTML(response.html);
		labbyContainer.append(html);
		//Close function
		$(".more-info-popup .close-btn").on("click", function(){
			$(html).remove();
		});
	};
	this.saveRequest = function(request, afterSaveFx)
	{
			
		var params = {
			request: request
		};
		var afterSave = function(response)
		{
			response = JSON.parse(response);
			if(util.handleResponseError(response))
			{
				return;
			}
			if(afterSaveFx)
			{
				afterSaveFx();
			}
		};
		$.post("requests/saveRequest", params, afterSave);
	};
	this.initShowItemsPopup = function(response)
	{
		var html = $.parseHTML(response.html);
		labbyContainer.append(html);
		//Close function
		$(".items-show-popup .cancel-btn").on("click", function(){
			$(html).remove();
		});
	};
	this.initCreatePopup = function(response)
	{
		
		var thisObj = this;
		var items = [];
		response.request = JSON.parse(response.request);
		response.request.items = {};
		var html = $.parseHTML(response.html);
		labbyContainer.append(html);
		
		var showItemsButton = $("#show-items-button");
		showItemsButton.removeAttr("id");
		var showToRequestButton = $("#show-to-request-button");
		showToRequestButton.removeAttr("id");

		var listContainer = $(".create-popup .list");
		var itemsContainer = $(".create-popup .available-items");
		var toRequestContainer = $(".create-popup .to-request");

		toRequestContainer.detach();

		showItemsButton.on("click", function()
		{
			showToRequestButton.removeClass("selected");
			showItemsButton.addClass("selected");
			toRequestContainer.detach();
			listContainer.append(itemsContainer);
		});

		showToRequestButton.on("click", function()
		{
			showItemsButton.removeClass("selected");
			showToRequestButton.addClass("selected");
			itemsContainer.detach();
			listContainer.append(toRequestContainer);
		});
		var updateHeader = function(amountOfItems, amountOfItemsToRequest)
		{
			showItemsButton.find(".amount").html("("+(amountOfItems)+")");
			showToRequestButton.find(".amount").html("("+(amountOfItemsToRequest)+")");
		};
		var amountOfItems;
		var amountOfItemsToRequest;
		var initItems = function()
		{
			var addOnClickEvent = function(item)
			{
				var id = item.id;
				$(item.button).on("click", function(){
					if(!item.toRequest)
					{
						
						var filters = util.filters();
						if($(item.requestTypeSelect).val() === response.types.existencias+"")
						{
							util.appendFilter({val: $(item.amountInput).val(), name: "Cantidad", filters: [filters.LESS_THAN], extraval: item.inStock, message: "La cantidad del item "+item.name +" debe ser menor o igual a "+item.inStock});	
						}
						
						util.appendFilter({val: $(item.amountInput).val(), name: "Cantidad", filters: [filters.GREATER_THAN], extraval: 0, message: "La cantidad del item "+item.name +" debe ser mayor a "+0});
						var afterFilterFx = function()
						{
							response.request.items[id] = {};
							response.request.items[id].amount = $(item.amountInput).val();
							response.request.items[id].type = $(item.requestTypeSelect).val();
							response.request.items[id].inStock = item.inStock;
							response.request.items[id].name = item.name;
							var typeDescription = $(".request-type option[value='"+item.requestTypeSelect.val()+"']").text();
							$(item.el).detach();
							$(item.requestTypeDiv).append($("<span class='type-text'>"+typeDescription+"</span>"));
							$(item.requestTypeSelect).detach();
							toRequestContainer.append(item.el);
							$(item.button).html("Quitar");
							$(item.amountInput).detach();
							$(item.amountDiv).html("<span class=\"label\">Cantidad: </span><span class=\"value\">"+$(item.amountInput).val()+"</span>");
							amountOfItems--;
							amountOfItemsToRequest++;
							item.toRequest = !item.toRequest;
						}
						util.runFilters(afterFilterFx);
					}
					else
					{
						delete response.request.items[id];
						$(item.el).detach();
						itemsContainer.append(item.el);
						$(item.button).html("Pedir");
						$(item.amountInput).insertBefore(item.button);
						$(item.amountDiv).html(item.itemAmountHTML);
						$(item.requestTypeDiv).find(".type-text").remove();
						$(item.requestTypeDiv).append(item.requestTypeSelect);
						amountOfItemsToRequest--;
						amountOfItems++;
						item.toRequest = !item.toRequest;
					}
					updateHeader(amountOfItems, amountOfItemsToRequest);
					
				});
				$(item.el).removeAttr("id");
			};
			//Form elements
			amountOfItems = $(".create-popup .item").length;
			amountOfItemsToRequest = amountOfItemsToRequest || 0;
			$(".create-popup  .available-items .item").each(function(){
				var item = {};
				item.el = this;
				item.button = $(this).find(".add-request");
				item.amountInput = $(this).find("input[name='amount']");
				item.inStock = $(this).find(".amount .value").html();
				item.amountDiv = $(this).find(".amount");
				item.nameDiv = $(this).find(".name");
				item.requestTypeDiv = $(this).find(".request-type-container");
				item.requestTypeSelect = $(this).find(".request-type");
				item.itemAmountHTML = $(item.amountDiv).html();
				item.toRequest = false;
				item.name = $(this).find(".name .value").html();
				item.id = $(item.el).attr("id").split("_")[1];
				addOnClickEvent(item);
				items.push(item);
			});
		}
		
		initItems();
		
		$(".create-popup .save-btn").on("click", function(){
			
			var filters = util.filters();
			if(util.isEmptyObject(response.request.items))
			{
				alert("Debes hacer pedido de al menos un item.");
				return;
			}
			for(var index in response.request.items)
			{
				if (!response.request.items.hasOwnProperty(index)) {
					continue;
				}
				var item = response.request.items[index];
				
				if(item.type === response.types.existencias)
				{
					util.appendFilter({val: item.amount, name: "Cantidad", filters: [filters.LESS_THAN], extraval: item.inStock, message: "La cantidad del item "+item.name +" debe ser menor o igual a "+item.inStock});
				}
				util.appendFilter({val: item.amount, name: "Cantidad", filters: [filters.GREATER_THAN], extraval: 0, message: "La cantidad del item "+item.name +" debe ser mayor a"+0});
				util.appendFilter({val: item.type, name: "'Tipo de pedido'", filters: [filters.NUMBERS_ONLY], message: "El campo 'Tipo de pedido' del item "+item.name+" tiene valores inválidos."}); 
			}

			var afterFilterFx = function()
			{
				var afterSave = function()
				{
					alert("La solicitud fue guardada con éxito");
					util.refresh("/requests");
				};
				thisObj.saveRequest(response.request, function(){afterSave();});
			};
			
			util.runFilters(afterFilterFx);
		});
		//Close function
		$(".create-popup .cancel-btn").on("click", function(){
			if(confirm("¿Está seguro?"))
			$(html).remove();
		});

		//Init filters
		
		var criteria = {};
		var addOnChange = function(el, id)
		{
			var id = $(el).attr("id");
			$(el).on("change", function()
			{
				criteria[id] = $(el).val();
			});
			$(el).removeAttr("id");
		};
		$(".create-popup .filter input").each(function(){			
			addOnChange(this);
		});
		$(".create-popup .filter .search").on("click", function(){
			var afterSearch = function(response)
			{
				
				response = JSON.parse(response);
				if(util.handleResponseError(response))
				{
					return;
				}
				var parent = $(itemsContainer).parent();
				parent.html("");
				parent.append(response.html);
				itemsContainer = $(".create-popup .available-items");
				amountOfItems = $(".create-popup .item").length;
				updateHeader(amountOfItems, amountOfItemsToRequest);
				initItems();
			};
			
			criteria.not = [];
			for(var i = 0; i < items.length; i++)
			{
				if(items[i].toRequest)
				{
					criteria.not.push(items[i].id);
				}
			}
			var params = {
				criteria: criteria
			};
			$.post("requests/searchItems", params, afterSearch);
		});
	};
	this.showItems = function(id)
	{
		var thisObj = this;
		var afterLoad = function(response)
		{
			
			var responseObject = JSON.parse(response);
			if(util.handleResponseError(responseObject))
			{
				return;
			}
			thisObj.initShowItemsPopup(responseObject);
		};
		var params = 
		{
			pk: id
		}
		$.post("requests/showItems", params, afterLoad);
	};
	this.showCreateRequest = function()
	{
		var thisObj = this;
		var afterLoad = function(response)
		{
			if(util.handleResponseError(response))
			{
				return;
			}
			response = JSON.parse(response);
			thisObj.initCreatePopup(response);
		};
		$.post('requests/createRequest', {}, afterLoad);
	};
	this.initRequestFilters = function()
	{
		var fromDateEl = $(".requests-filter .from input");
		var toDateEl = $(".requests-filter .to input");
		var statusEl = $(".requests-filter .status select");

		var fromDate = $(fromDateEl).val();
		var toDate = $(toDateEl).val();
		var status = $(statusEl).val();

		fromDateEl.on("change", function(){
			fromDate = $(this).val();
		});

		toDateEl.on("change", function(){
			toDate = $(this).val();
		});

		statusEl.on("change", function(){
			status = $(this).val();
		});

		$(".requests-filter .controls a").on("click", function(){
			var url = "requests";
			url = fromDate === "" ? url : util.addUrlParam(url, "from", fromDate);
			url = toDate === "" ? url : util.addUrlParam(url, "to", toDate);
			url = status === "" ? url : util.addUrlParam(url, "status", status);
			util.goTo(url);
		});
	};
	this.initRequestNewItem = function(response)
	{
		
		var thisObj = this;
		var html = $.parseHTML(response.html);
		labbyContainer.append(html);
		var itemRequest = {
			reference: "",
			name: "",
			comment: "",
			admin: $("#admin").val()
		};
		var addOnChange = function(el, propertyName)
		{
			$(el).on("change", function(){
				itemRequest[propertyName] = $(this).val();
			});

			$(el).removeAttr("id");
		};

		var thePopup = $(".new-item-request-popup");
		addOnChange($("#reference"), "reference");
		addOnChange($("#name"), "name");
		addOnChange($("#comment"), "comment");
		addOnChange($("#admin"), "admin");

		$(thePopup).find(".cancel-btn").on("click", function(){
			$(html).remove();
		});

		$(thePopup).find(".send-btn").on("click", function(){
			debugger;
			var filters = util.filters();
			util.appendFilter({val: itemRequest.reference, name: "Referencia", filters: [filters.MAX_SIZE], extraval: 255});
			util.appendFilter({val: itemRequest.name, name: "Nombre", filters: [filters.MAX_SIZE], extraval: 255});
			util.appendFilter({val: itemRequest.name, name: "Comentario", filters: [filters.MAX_SIZE], extraval: 255, canBeEmpty: true});
			var afterFilters = function()
			{
				var afterSendRequest = function(response)
				{
					response = JSON.parse(response);
					if(util.handleResponseError(response))
					{
						return;
					}
					alert("La solicitud ha sido enviada al administrador.");
					util.refresh("/requests");
				};
				$.post("requests/sendNewItemRequest", itemRequest, afterSendRequest);
			};

			util.runFilters(afterFilters);
		});
	};
	this.showRequestNewItem = function()
	{
		var thisObj = this;
		var afterLoad = function(response)
		{
			
			var response = JSON.parse(response);
			if(util.handleResponseError(response))
			{
				return;
			}
			thisObj.initRequestNewItem(response);
		};
		$.post("requests/requestNewItem", {}, afterLoad);
	};
	this.init = function()
	{
		var thisObj = this;
		$("#requests-table tbody tr").each(function()
		{
			
			var theTr = this;
			var id = $(theTr).attr("id");
			var showItemsBtn = $(theTr).find("a[class='btn items']");
			//var editBtn = $(theTr).find("a[class='btn edit']");
			//var deleteBtn = $(theTr).find("a[class='btn delete']");

			showItemsBtn.on("click", function()
			{
				
				thisObj.showItems(id);
			});
			/*editBtn.on("click", function()
			{
				thisObj.showEditRequest(id);
			});
			deleteBtn.on("click", function()
			{
				thisObj.showDeleteRequest(id);
			});*/
			$(theTr).removeAttr("id");
		});
		
		$(".request-options .create").on("click", function(){
			thisObj.showCreateRequest();
		});

		$(".request-options .request-new-item").on("click", function(){
			thisObj.showRequestNewItem();
		});
	};
	this.init();
	this.initRequestFilters();
}

var rq = new Requests();